package com.huiminpay.transaction.controller;

import com.alibaba.fastjson.JSON;
import com.huiminpay.common.cache.domain.BrowserType;
import com.huiminpay.common.cache.util.AmountUtil;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.IPUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.vo.OrderConfirmVO;
import com.huiminpay.transaction.api.TransactionService;
import com.huiminpay.transaction.api.dto.PayOrderDTO;
import com.huiminpay.transaction.convert.PayOrderConvert;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
public class PayController {

    @Reference
    AppService appService;
    @Autowired
    TransactionService transactionService;

    /**
     * \* 支付入口
     * \* @param ticket
     * \* @param type
     * \* @param request
     * \* @return
     */
//    @RequestMapping(value = "/pay-entry/{ticket}")
//    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request) {
//        return "forward:/pay-page";
//    }
    @RequestMapping(value = "/pay-entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request) {

        try {
            //将ticket的base64还原
            String ticketStr = EncryptUtil.decodeUTF8StringBase64(ticket);
            //将ticket（json）转成对象
            PayOrderDTO order = JSON.parseObject(ticketStr, PayOrderDTO.class);
            //将对象转成url格式
            // String url = toParamsString(order);
            BrowserType browserType = BrowserType.valueOfUserAgent(request.getHeader("user‐agent"));
            switch (browserType) {
                case ALIPAY: //直接跳转收银台pay.html
                case MOBILE_BROWSER: //直接跳转收银台pay.html
                    return "forward:/pay-page?" + ParseURLPairUtil.parseURLPair(order);
                case WECHAT: //获取授权码(待实现)
                    return "forward:/pay-page?" + ParseURLPairUtil.parseURLPair(order);
                default:
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return "forward:/pay-page-error";
    }


    @ApiOperation("支付宝门店下单付款")
    @PostMapping("/createAliPayOrder")
    public void createAlipayOrderForStore(OrderConfirmVO orderConfirmVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 支付宝的下单接口,前端订单确认页面，点击确认支付，请求进来
        PayOrderDTO payOrderDTO = PayOrderConvert.INSTANCE.vo2dto(orderConfirmVO);
        //应用id
        String appId = payOrderDTO.getAppId();
        //获取下单的应用信息
        AppDTO app = appService.getAppById(appId);
        payOrderDTO.setMerchantId(app.getMerchantId());//商户id
        //将前端输入的 元转成分
        payOrderDTO.setTotalAmount(Integer.parseInt(AmountUtil.changeY2F(orderConfirmVO.getTotalAmount().toString())));
        //客户端ip
        payOrderDTO.setClientIp(IPUtil.getIpAddr(request));
        //保存订单，调用支付渠道代理服务的支付宝下单
        PaymentResponseDTO<String> paymentResponseDTO = transactionService.submitOrderByAli(payOrderDTO);
        //支付宝下单接口响应
        String content = paymentResponseDTO.getContent();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(content);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }
}